<template>
  <div class="admin-container">
    <!-- 顶部导航栏 -->
    <div class="admin-header glass">
      <div class="header-left">
        <h1>🎓 趣味英语 - 管理后台</h1>
        <span class="admin-badge">{{ userStore.user?.role === 'super_admin' ? '超级管理员' : '管理员' }}</span>
      </div>
      <div class="header-right">
        <el-dropdown>
          <div class="admin-info">
            <span>{{ userStore.user?.real_name || userStore.user?.username }}</span>
            <el-icon><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 侧边栏 + 内容区 -->
    <div class="admin-main">
      <!-- 侧边栏 -->
      <div class="admin-sidebar glass">
        <el-menu
          :default-active="activeMenu"
          class="admin-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="dashboard">
            <el-icon><DataLine /></el-icon>
            <span>数据概览</span>
          </el-menu-item>
          <el-menu-item index="users">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>
          <el-menu-item index="vocabulary">
            <el-icon><Reading /></el-icon>
            <span>单词管理</span>
          </el-menu-item>
          <el-menu-item index="achievements">
            <el-icon><Trophy /></el-icon>
            <span>成就管理</span>
          </el-menu-item>
          <el-menu-item index="logs">
            <el-icon><Document /></el-icon>
            <span>操作日志</span>
          </el-menu-item>
          <el-menu-item index="settings" v-if="userStore.user?.role === 'super_admin'">
            <el-icon><Setting /></el-icon>
            <span>系统设置</span>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 内容区 -->
      <div class="admin-content">
        <!-- 数据概览 -->
        <div v-if="activeMenu === 'dashboard'" class="content-section">
          <h2>📊 数据概览</h2>
          <div class="stats-grid">
            <div class="stat-card glass">
              <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
                <el-icon size="30"><User /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.totalUsers }}</div>
                <div class="stat-label">总用户数</div>
              </div>
            </div>
            <div class="stat-card glass">
              <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%)">
                <el-icon size="30"><Reading /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">848</div>
                <div class="stat-label">单词总数</div>
              </div>
            </div>
            <div class="stat-card glass">
              <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)">
                <el-icon size="30"><Trophy /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.totalAchievements }}</div>
                <div class="stat-label">总成就数</div>
              </div>
            </div>
            <div class="stat-card glass">
              <div class="stat-icon" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)">
                <el-icon size="30"><DataLine /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.todayActive }}</div>
                <div class="stat-label">今日活跃</div>
              </div>
            </div>
          </div>

          <div class="welcome-message glass">
            <h3>👋 欢迎回来，{{ userStore.user?.real_name }}！</h3>
            <p>您的权限级别：<strong>{{ userStore.user?.role }}</strong></p>
            <p>上次登录：刚刚</p>
          </div>
        </div>

        <!-- 用户管理 -->
        <div v-if="activeMenu === 'users'" class="content-section">
          <h2>👥 用户管理</h2>
          <div class="toolbar">
            <el-input v-model="userSearch" placeholder="搜索用户..." style="width: 300px" clearable />
            <el-button type="primary" @click="loadUsers" :loading="loading">刷新</el-button>
          </div>
          <el-table :data="filteredUsers" class="glass-table" v-loading="loading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="username" label="用户名" width="150" />
            <el-table-column prop="school" label="学校" />
            <el-table-column prop="grade" label="年级" width="100" />
            <el-table-column prop="stars" label="⭐星星" width="100" />
            <el-table-column prop="continuous_days" label="🔥连续天数" width="120" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="viewUserDetail(row)">详情</el-button>
                <el-button size="small" type="danger" @click="confirmDeleteUser(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 单词管理 -->
        <div v-if="activeMenu === 'vocabulary'" class="content-section">
          <h2>📖 单词管理</h2>
          <div class="toolbar">
            <el-input v-model="wordSearch" placeholder="搜索单词..." style="width: 250px" clearable />
            <el-select v-model="gradeFilter" placeholder="筛选年级" style="width: 150px" clearable>
              <el-option label="全部年级" value="" />
              <el-option label="三上" value="三上" />
              <el-option label="三下" value="三下" />
              <el-option label="四上" value="四上" />
              <el-option label="四下" value="四下" />
              <el-option label="五上" value="五上" />
              <el-option label="五下" value="五下" />
              <el-option label="六上" value="六上" />
              <el-option label="六下" value="六下" />
            </el-select>
            <el-button type="primary" @click="loadWords" :loading="loading">刷新</el-button>
          </div>
          <el-table :data="filteredWords" class="glass-table" v-loading="loading" max-height="600">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="word" label="单词" width="150" />
            <el-table-column prop="phonetic" label="音标" width="150" />
            <el-table-column prop="chinese" label="中文" />
            <el-table-column prop="grade" label="年级" width="100" />
            <el-table-column prop="unit" label="单元" width="120" />
          </el-table>
          <div class="pagination">
            <span>共 {{ words.length }} 个单词</span>
          </div>
        </div>

        <!-- 成就管理 -->
        <div v-if="activeMenu === 'achievements'" class="content-section">
          <h2>🏆 成就管理</h2>
          <div class="achievements-scroll-container">
            <div class="achievements-grid">
              <div class="achievement-card glass" v-for="achievement in achievementsList" :key="achievement.id">
                <div class="achievement-icon">{{ achievement.icon }}</div>
                <h4>{{ achievement.name }}</h4>
                <p class="achievement-description">{{ achievement.description }}</p>
                <p class="achievement-condition">条件: {{ achievement.condition }}</p>
                <el-tag :type="achievement.enabled ? 'success' : 'info'">
                  {{ achievement.enabled ? '已启用' : '未启用' }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作日志 -->
        <div v-if="activeMenu === 'logs'" class="content-section">
          <h2>📋 操作日志</h2>
          <el-table :data="mockLogs" class="glass-table" max-height="600">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="admin" label="管理员" width="120" />
            <el-table-column prop="action" label="操作" width="150" />
            <el-table-column prop="details" label="详情" />
            <el-table-column prop="time" label="时间" width="180" />
          </el-table>
        </div>

        <!-- 系统设置 -->
        <div v-if="activeMenu === 'settings'" class="content-section">
          <h2>⚙️ 系统设置</h2>
          <div class="settings-grid">
            <div class="setting-item glass">
              <h4>📧 邮件通知</h4>
              <el-switch v-model="settings.emailNotification" />
              <p>启用邮件通知功能</p>
            </div>
            <div class="setting-item glass">
              <h4>🔔 系统公告</h4>
              <el-switch v-model="settings.systemAnnouncement" />
              <p>显示系统公告栏</p>
            </div>
            <div class="setting-item glass">
              <h4>🚀 自动备份</h4>
              <el-switch v-model="settings.autoBackup" />
              <p>每日自动备份数据</p>
            </div>
            <div class="setting-item glass">
              <h4>🎨 主题颜色</h4>
              <el-select v-model="settings.theme" placeholder="选择主题">
                <el-option label="紫色梦幻" value="purple" />
                <el-option label="蓝色海洋" value="blue" />
                <el-option label="粉色甜心" value="pink" />
              </el-select>
            </div>
          </div>
          <div style="margin-top: 30px; text-align: center;">
            <el-button type="primary" size="large" @click="saveSettings">保存设置</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, DataLine, User, Reading, Trophy, Document, Setting } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { achievementApi } from '@/api/achievement'

const router = useRouter()
const userStore = useUserStore()

const activeMenu = ref('dashboard')
const loading = ref(false)

const stats = ref({
  totalUsers: 0,
  totalAchievements: 32,
  todayActive: 0
})

// 用户管理
const users = ref<any[]>([])
const userSearch = ref('')

const filteredUsers = computed(() => {
  if (!userSearch.value) return users.value
  return users.value.filter(u => 
    u.username.includes(userSearch.value) || 
    u.school?.includes(userSearch.value)
  )
})

// 单词管理
const words = ref<any[]>([])
const wordSearch = ref('')
const gradeFilter = ref('')

const filteredWords = computed(() => {
  let result = words.value
  if (wordSearch.value) {
    result = result.filter(w => 
      w.word.toLowerCase().includes(wordSearch.value.toLowerCase()) ||
      w.chinese.includes(wordSearch.value)
    )
  }
  if (gradeFilter.value) {
    result = result.filter(w => w.grade === gradeFilter.value)
  }
  return result
})

// 操作日志模拟数据
const mockLogs = ref([
  { id: 1, admin: 'admin', action: '登录系统', details: '管理员登录', time: '2025-10-12 15:30:00' },
  { id: 2, admin: 'admin', action: '查看用户', details: '查看用户列表', time: '2025-10-12 15:31:00' },
  { id: 3, admin: 'admin', action: '查看单词', details: '查看单词管理', time: '2025-10-12 15:32:00' }
])

// 系统设置
const settings = ref({
  emailNotification: true,
  systemAnnouncement: true,
  autoBackup: false,
  theme: 'purple'
})

// 成就列表
const achievementsList = ref([])

// 图标映射
const iconMap: Record<string, string> = {
  beginner: '🎯',
  study: '📚',
  master: '🏆',
  game: '🎮',
  crown: '👑',
  star: '⭐',
  pet: '🐾',
  friend: '👥',
  perfect: '💯',
  streak: '🔥',
  learn: '📖',
  // 数据库中的图标名称映射
  book: '📚',
  medal: '🏅',
  trophy: '🏆',
  task: '✅',
  fire: '🔥',
  target: '🎯',
  hundred: '💯',
  paw: '🐾',
  people: '👥',
  rocket: '🚀',
  gem: '💎'
}

// 加载成就列表
const loadAchievements = async () => {
  try {
    const res = await achievementApi.getAllAchievements()
    if (res.success && res.data) {
      achievementsList.value = res.data.map((a: any) => ({
        id: a.id,
        icon: iconMap[a.icon] || a.icon || '🎯',
        name: a.name,
        description: a.description,
        condition: `${a.type} ≥ ${a.target}`,
        enabled: a.enabled
      }))
    }
  } catch (error) {
    console.error('加载成就列表失败:', error)
  }
}

// 监听年级筛选变化
watch(gradeFilter, () => {
  // filteredWords computed会自动更新
  console.log('年级筛选已更改为:', gradeFilter.value)
})

// 监听菜单切换
watch(activeMenu, async (newMenu) => {
  if (newMenu === 'vocabulary' && words.value.length === 0) {
    await loadWords()
  } else if (newMenu === 'users' && users.value.length === 0) {
    await loadUsers()
  } else if (newMenu === 'achievements' && achievementsList.value.length === 0) {
    await loadAchievements()
  }
})

onMounted(async () => {
  // 检查是否是管理员
  if (!userStore.user?.isAdmin) {
    ElMessage.error('您没有管理员权限')
    router.push('/dashboard')
    return
  }

  // 加载统计数据
  await loadStats()
  
  // 加载系统设置
  const savedSettings = localStorage.getItem('admin_settings')
  if (savedSettings) {
    settings.value = JSON.parse(savedSettings)
  }
})

const loadStats = async () => {
  try {
    const res = await request.get('/admin/stats')
    if (res.success && res.data) {
      stats.value = {
        totalUsers: res.data.totalUsers,
        totalAchievements: res.data.totalAchievements,
        todayActive: res.data.todayActive
      }
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    // 使用默认值
    stats.value = {
      totalUsers: 0,
      totalAchievements: 32,
      todayActive: 0
    }
  }
}

const handleMenuSelect = async (index: string) => {
  activeMenu.value = index
  
  if (index === 'users' && users.value.length === 0) {
    await loadUsers()
  } else if (index === 'vocabulary' && words.value.length === 0) {
    await loadWords()
  }
}

const loadUsers = async () => {
  try {
    loading.value = true
    const res = await request.get('/admin/users')
    if (res.success && res.data) {
      users.value = res.data.users || res.data
    }
  } catch (error: any) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

const loadWords = async () => {
  try {
    loading.value = true
    // 获取所有年级的单词
    const allGrades = ['三上', '三下', '四上', '四下', '五上', '五下', '六上', '六下']
    const allWords: any[] = []
    
    for (const grade of allGrades) {
      try {
        const res = await request.get('/vocabulary', { 
          params: { grade, limit: 200 } 
        })
        if (res.success && res.data) {
          // 检查res.data是否是数组
          if (Array.isArray(res.data)) {
            allWords.push(...res.data)
          } else if (res.data.words && Array.isArray(res.data.words)) {
            // 如果是对象格式 {words: [...], total: ...}
            allWords.push(...res.data.words)
          } else {
            console.warn(`${grade} 返回的数据格式不正确:`, res.data)
          }
        }
      } catch (err) {
        console.error(`加载 ${grade} 单词失败:`, err)
      }
    }
    
    words.value = allWords
    console.log(`✅ 成功加载 ${allWords.length} 个单词`)
    
    if (allWords.length === 0) {
      ElMessage.warning('未能加载任何单词')
    } else {
      ElMessage.success(`已加载 ${allWords.length} 个单词`)
    }
  } catch (error: any) {
    console.error('加载单词列表失败:', error)
    ElMessage.error('加载单词列表失败')
  } finally {
    loading.value = false
  }
}

const viewUserDetail = async (user: any) => {
  try {
    loading.value = true
    const res = await request.get(`/admin/users/${user.id}`)
    if (res.success) {
      const userData = res.data.user
      const pet = res.data.pet
      const achievements = res.data.achievements || []
      
      ElMessageBox.alert(`
        <div style="text-align: left;">
          <h3>👤 ${userData.username}</h3>
          <p><strong>学校：</strong>${userData.school || '未设置'}</p>
          <p><strong>年级：</strong>${userData.grade}</p>
          <p><strong>⭐星星：</strong>${userData.stars}</p>
          <p><strong>🔥连续天数：</strong>${userData.continuous_days}天</p>
          <p><strong>📚已学单词：</strong>${userData.words_learned || 0}个</p>
          <p><strong>✅正确数：</strong>${userData.total_correct}</p>
          <p><strong>❌错误数：</strong>${userData.total_wrong}</p>
          <p><strong>📊平均掌握度：</strong>${userData.avg_mastery ? parseFloat(userData.avg_mastery).toFixed(1) : 0}%</p>
          ${pet ? `<p><strong>🐾宠物：</strong>${pet.pet_name} (Lv.${pet.level})</p>` : ''}
          <p><strong>🏆成就数：</strong>${achievements.length}个</p>
          <p><strong>⏰注册时间：</strong>${new Date(userData.created_at).toLocaleString()}</p>
        </div>
      `, '用户详情', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '关闭'
      })
    }
  } catch (error: any) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
  } finally {
    loading.value = false
  }
}

const confirmDeleteUser = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    loading.value = true
    const res = await request.delete(`/admin/users/${user.id}`)
    if (res.success) {
      ElMessage.success('删除成功')
      await loadUsers()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  } finally {
    loading.value = false
  }
}

const saveSettings = () => {
  ElMessage.success('设置已保存')
  // 系统设置功能已实现（本地存储）
  localStorage.setItem('admin_settings', JSON.stringify(settings.value))
}

const logout = () => {
  userStore.logout()
  router.push('/login')
}
</script>

<style scoped lang="scss">
.admin-container {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
}

.admin-header {
  height: 70px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  margin-bottom: 20px;

  .header-left {
    display: flex;
    align-items: center;
    gap: 15px;

    h1 {
      margin: 0;
      font-size: 1.5rem;
      color: white;
    }

    .admin-badge {
      padding: 5px 15px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 20px;
      color: white;
      font-size: 0.9rem;
    }
  }

  .header-right {
    .admin-info {
      display: flex;
      align-items: center;
      gap: 10px;
      color: white;
      cursor: pointer;
      padding: 10px 15px;
      border-radius: 8px;
      transition: all 0.3s;

      &:hover {
        background: rgba(255, 255, 255, 0.1);
      }
    }
  }
}

.admin-main {
  display: flex;
  gap: 20px;
  padding: 0 20px 20px;
  min-height: calc(100vh - 110px);
}

.admin-sidebar {
  width: 250px;
  padding: 20px;
  border-radius: 15px;

  .admin-menu {
    background: transparent;
    border: none;

    :deep(.el-menu-item) {
      color: rgba(255, 255, 255, 0.8);
      margin-bottom: 5px;
      border-radius: 8px;

      &:hover {
        background: rgba(255, 255, 255, 0.1);
        color: white;
      }

      &.is-active {
        background: rgba(255, 255, 255, 0.2);
        color: white;
      }
    }
  }
}

.admin-content {
  flex: 1;
  padding: 30px;
  border-radius: 15px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);

  h2 {
    color: white;
    margin-bottom: 20px;
    font-size: 1.8rem;
  }
}

.content-section {
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
  }

  .stat-card {
    padding: 25px;
    border-radius: 15px;
    display: flex;
    align-items: center;
    gap: 20px;

    .stat-icon {
      width: 70px;
      height: 70px;
      border-radius: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
    }

    .stat-info {
      .stat-value {
        font-size: 2rem;
        font-weight: bold;
        color: white;
      }

      .stat-label {
        color: rgba(255, 255, 255, 0.7);
        font-size: 0.9rem;
        margin-top: 5px;
      }
    }
  }

  .welcome-message {
    padding: 30px;
    border-radius: 15px;

    h3 {
      color: white;
      margin-bottom: 15px;
    }

    p {
      color: rgba(255, 255, 255, 0.8);
      margin: 8px 0;

      strong {
        color: white;
      }
    }
  }
}

.toolbar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.glass-table {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  
  :deep(.el-table) {
    background: transparent !important;
    
    th, td {
      background: transparent !important;
      color: white !important;
      border-color: rgba(255, 255, 255, 0.1) !important;
    }
    
    tr:hover > td {
      background: rgba(255, 255, 255, 0.1) !important;
    }
  }
}

.pagination {
  margin-top: 20px;
  text-align: center;
  color: white;
  font-size: 1.1rem;
}

.achievements-scroll-container {
  max-height: calc(100vh - 250px);
  overflow-y: auto;
  padding-right: 10px;
  
  /* 自定义滚动条样式 */
  &::-webkit-scrollbar {
    width: 8px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 10px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.3);
    border-radius: 10px;
    
    &:hover {
      background: rgba(255, 255, 255, 0.5);
    }
  }
}

.achievements-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.achievement-card {
  padding: 25px;
  text-align: center;
  border-radius: 15px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
  }

  .achievement-icon {
    font-size: 4rem;
    margin-bottom: 15px;
  }

  h4 {
    color: white;
    margin: 10px 0;
    font-size: 1.3rem;
    font-weight: bold;
  }

  .achievement-description {
    color: rgba(255, 255, 255, 0.9);
    font-size: 1rem;
    margin-bottom: 10px;
  }

  .achievement-condition {
    color: rgba(255, 255, 255, 0.7);
    font-size: 0.85rem;
    margin-bottom: 15px;
    font-style: italic;
  }
}

.settings-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 25px;
  margin-bottom: 20px;
}

.setting-item {
  padding: 30px;
  border-radius: 15px;
  text-align: center;

  h4 {
    color: white;
    font-size: 1.3rem;
    margin-bottom: 20px;
  }

  p {
    color: rgba(255, 255, 255, 0.8);
    font-size: 0.95rem;
    margin-top: 15px;
  }

  .el-switch {
    --el-switch-on-color: #13ce66;
    --el-switch-off-color: #ff4949;
  }
}
</style>

